package ru.ncedu.java.dmsi.robots.model;

import java.util.HashMap;
import java.util.Map;

public class PointFactory {
    private static final PointFactory pointFactory = new PointFactory();
    private Map<Integer, Map<Integer, Point>> cash; // Map(X, Map(Y)) -> Point(X, Y)

    private PointFactory() {
        if (pointFactory != null)
            throw new IllegalThreadStateException();
    }
    public static PointFactory getInstance() {
        return pointFactory;
    }
    public Point getPoint( int x, int y ) {
        if (cash == null) { // Cash is empty
            cash = new HashMap<Integer, Map<Integer, Point>>();
            Point p = new Point(x, y);
            cash.put(x, new HashMap<Integer, Point>());
            cash.get(x).put(y, p);
            return p;
        }
        if (cash.containsKey(x)) {
            if (cash.get(x).containsKey(y))
                return cash.get(x).get(y); // Point exist in cash
            Point p = new Point(x, y); // Point not exist in cash, but there is a point with similar 'x' coordinate
            cash.get(x).put(y, p);
            return p;
        }
        // point has not similar in cash
        Point p = new Point(x, y);
        cash.put(x, new HashMap<Integer, Point>());
        cash.get(x).put(y, p);
        return p;
    }
}
